package com.play.ballen.synthetic.dialog

import android.app.Dialog
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.LayoutInflater
import android.view.WindowManager
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hjq.toast.ToastUtils
import com.play.ballen.R
import com.play.ballen.pack.entity.PackBallInfo
import com.play.ballen.synthetic.adapter.SyntheticDialogBallAdapter
import com.yuven.baselib.utils.ResourceUtil

class SyntheticDialogUtils(private val mContext: Context) {

    private lateinit var dialog: Dialog

    private val adapter: SyntheticDialogBallAdapter by lazy {
        SyntheticDialogBallAdapter(arrayListOf())
    }

    var valueCallback: ((select: PackBallInfo) -> Unit)? = null

    fun show(
        items: List<PackBallInfo>?,
        id1Selected: String,
        id2Selected: String,
        id3Selected: String
    ) {
        if (items.isNullOrEmpty()) {
            return
        }
        if (!this::dialog.isInitialized) {
            val view =
                LayoutInflater.from(mContext).inflate(R.layout.dialog_synthetic_choose, null)
            val rv = view.findViewById<RecyclerView>(R.id.rv)
            view.findViewById<ImageView>(R.id.imgClose).setOnClickListener { dialog.dismiss() }

            rv.layoutManager = LinearLayoutManager(mContext)
            rv.adapter = adapter
            adapter.setOnItemClickListener { a, view, position ->
                val info = adapter.data[position]
                if (info.id == adapter.id1Selected || info.id == adapter.id2Selected || info.id == adapter.id3Selected) {
                    ToastUtils.show(ResourceUtil.getString(R.string.synthetic_other_choose_tip))
                    return@setOnItemClickListener
                }

                valueCallback?.invoke(info)
                dialog.dismiss()
            }

            dialog = Dialog(mContext)
            dialog.setContentView(view)
            dialog.setCanceledOnTouchOutside(true)
            dialog.window?.setLayout(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT
            )
            dialog.window?.setBackgroundDrawable(ColorDrawable())
        }

        adapter.id1Selected = id1Selected
        adapter.id2Selected = id2Selected
        adapter.id3Selected = id3Selected

        adapter.setList(items)

        if (!dialog.isShowing) {
            dialog.show()
        }
    }

}